package com.quyou.funtour.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quyou.funtour.bean.ResultInfo;
import com.quyou.funtour.bean.WechatRespoonse;
import com.quyou.funtour.po.UserPo;
import com.quyou.funtour.service.UserService;
import com.quyou.funtour.utils.FileToUtil;
import com.quyou.funtour.utils.WechatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.UUID;

/**
 * 用户接口
 */
@Controller
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private WechatUtils wechatUtils;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    /**
     * 用户登录
     * @param code 获取微信session
     * @param user 用户信息
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public ResultInfo login(String code, UserPo user){
        if(user==null || user.equals(new UserPo())){
            return ResultInfo.no("用户信息不能为空");
        }
        WechatRespoonse wechatRespoonse = wechatUtils.login(code);
        if(wechatRespoonse==null){
            return ResultInfo.no("获取登录信息失败！！");
        }
        //拼接得到的session与openid
        String msg = wechatRespoonse.getSession_key()+":"+wechatRespoonse.getOpenid();
        user.setOpenId(wechatRespoonse.getOpenid());
        return ResultInfo.ok(msg,userService.login(user, msg));
    }

    /**
     * 修改用户
     * @param userPo
     * @return
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public ResultInfo updateUser
    (
            @RequestHeader("3rd_session")String rdSession
            , UserPo userPo
    )
    {
        //String attribute = (String) session.getAttribute("3rd_session");
        Object o = redisTemplate.opsForValue().get(rdSession);
        if(o==null){
            return ResultInfo.no("获取失败，请重新登录");
        }
        boolean b = userService.updateById(userPo);
        if(b){
            return ResultInfo.ok("修改成功");
        }else {
            return ResultInfo.no("修改失败");
        }
    }

    /**
     * 修改用户
     * @param userPo
     * @return
     */
    @RequestMapping("/adminUpdateUser")
    @ResponseBody
    public ResultInfo adminUpdateUser(UserPo userPo) {
        boolean b = userService.updateById(userPo);
        if(b){
            return ResultInfo.ok("修改成功");
        }else {
            return ResultInfo.no("修改失败");
        }
    }

    /**
     * 上传图片
     * @param file
     * @return
     */
    @RequestMapping("/uploadImg")
    @ResponseBody
    public ResultInfo uploadImg(MultipartFile file){
        try {
            //System.out.println("发送文件:"+file.getOriginalFilename());
            String imgPath = FileToUtil.updateImg(file.getOriginalFilename(), file.getInputStream());
            return ResultInfo.ok(imgPath);
        } catch (IOException e) {
            return ResultInfo.no("上传失败");
        }
    }

    /**
     * 后台管理登录
     * @param username 用户名（quyouadmin）
     * @param password 密码（quyouadmin）
     * @return
     */
    @RequestMapping("/adminLogin")
    @ResponseBody
    public ResultInfo adminLogin(String username,String password,HttpSession session){
        if(username.equals("quyouadmin") && password.equals("quyouadmin")){
            String token = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            session.setAttribute("admin_login_user",token);
            return ResultInfo.ok("登录成功",token);
        }else {
            return ResultInfo.no("用户名或者密码错误！！！");
        }
    }

    /**
     * 获取用户分页集合
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/userPoList")
    @ResponseBody
    public ResultInfo userPoList(@RequestParam("current") Integer current,@RequestParam("size") Integer size){
        Page<UserPo> userPoPage = new Page<>(current,size);
        Page<UserPo> page = userService.page(userPoPage);
        return ResultInfo.ok(page);
    }

    /**
     * 根据id获取用户数据
     * @param id
     * @return
     */
    @GetMapping("/getUserById/{uid}")
    @ResponseBody
    public ResultInfo getUserById(@PathVariable("uid") String id){
        UserPo byId = userService.getById(id);
        if(byId==null){
            return ResultInfo.no("获取用户失败");
        }else {
            return ResultInfo.ok(byId);
        }
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @PostMapping("/addUser")
    @ResponseBody
    public ResultInfo addUser(UserPo user){
        boolean save = userService.save(user);
        if(save){
            return ResultInfo.ok("保存成功");
        }else {
            return ResultInfo.no("保存失败");
        }
    }

    /**
     * 修改用户
     * @return
     */
    @PostMapping("/updateUser")
    @ResponseBody
    public ResultInfo updateUser(UserPo user){
        boolean b = userService.updateById(user);
        if(b){
            return ResultInfo.ok("修改成功");
        }else {
            return ResultInfo.no("修改失败");
        }
    }

    /**
     * 删除用户
     * @param uid
     * @return
     */
    @DeleteMapping("/deleteUser/{uid}")
    @ResponseBody
    public ResultInfo deleteUser(@PathVariable("uid") String uid){
        boolean b = userService.removeById(uid);
        if(b){
            return ResultInfo.ok("删除成功");
        }else {
            return ResultInfo.no("删除失败");
        }
    }

    /**
     * 模糊查询
     * @param current 当前页
     * @param size 每页显示条数
     * @param like 模糊条件
     * @return
     */
    @GetMapping("/likeUser")
    @ResponseBody
    public ResultInfo likeUser(@RequestParam("current") Integer current,
                               @RequestParam("size") Integer size,
                               @RequestParam("like")String like){
        Page<UserPo> userPoPage = new Page<>(current,size);
        QueryWrapper<UserPo> queryWrapper = new QueryWrapper<UserPo>()
                .like("wx_name", like).or()
                .like("user_class", like).or()
                .like("student_number", like).or()
                .like("phone", like).or()
                .like("gender", like).or()
                .like("qq_num", like);
        Page<UserPo> page = userService.page(userPoPage, queryWrapper);
        return ResultInfo.ok(page);
    }

}
